package com.fjwt.gz.util;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {
    public static MultipartFile convert(String imageUrl) throws IOException {
        // 将在线图片地址转换为URL对象
        URL url = new URL(imageUrl);
        // 打开URL连接
        URLConnection connection = url.openConnection();
        // 转换为HttpURLConnection对象
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        // 获取输入流
        InputStream inputStream = httpURLConnection.getInputStream();
        // 读取输入流中的数据，并保存到字节数组中
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        // 将字节数组转换为字节数组
        byte[] bytes = byteArrayOutputStream.toByteArray();
        // 创建ByteArrayInputStream对象，将字节数组传递给它
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        // 创建MultipartFile对象，将ByteArrayInputStream对象作为构造函数的参数
        MultipartFile multipartFile = new MockMultipartFile("file",imageUrl.substring(imageUrl.lastIndexOf("/")+1) , null, byteArrayInputStream);
        return multipartFile;
    }
}
